//
//  GroupDetailsViewController.swift
//  puretennis
//
//  Created by IYE Technologies on 11/22/14.
//  Copyright (c) 2014 IYE Technologies. All rights reserved.
//

import UIKit



class GroupDetailsAsOwnerViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!;
    var groupInfo:NSDictionary!;
    var ownerGuid:String!;
    var dataSource:[NSMutableDictionary] = [];
    var groupParticipantsAmount = 1;
    override func viewDidLoad() {
        super.viewDidLoad()
        ViewUtils.addBackgroundView(self);
        self.tableView.dataSource = self;
        self.tableView.delegate = self;
        self.tableView.layer.masksToBounds = true;
        self.tableView.layer.cornerRadius = 4;
        self.initNavigationItem();
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated);
        self.hideTabBar();
        var groupGuid = self.groupInfo.objectForKey("guid") as String;
        self.loadGroupDetails(groupGuid);
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated);
        self.updateTitile();
    }
    
    func setup(group:NSDictionary){
        self.groupInfo = group;
    }
    
    func initNavigationItem(){
        var backButton = UIButton();
        backButton.setImage(UIImage(named: "back"), forState: UIControlState.Normal);
        backButton.addTarget(self, action: Selector("back:"), forControlEvents: UIControlEvents.TouchUpInside);
        backButton.showsTouchWhenHighlighted = true;
        backButton.contentMode = UIViewContentMode.Left;
        backButton.sizeToFit();
        var backBarButtonItem = UIBarButtonItem(customView: backButton);
        self.navigationItem.leftBarButtonItem = backBarButtonItem;
        
        var menuButton = UIButton();
        menuButton.setImage(UIImage(named: "arrow"), forState: UIControlState.Normal);
        menuButton.addTarget(self, action: Selector("openMenu:"), forControlEvents: UIControlEvents.TouchUpInside);
        menuButton.showsTouchWhenHighlighted = true;
        menuButton.contentMode = UIViewContentMode.Left;
        menuButton.sizeToFit();
        var menuNavBarButtonItem = UIBarButtonItem(customView: menuButton);
        self.navigationItem.rightBarButtonItem = menuNavBarButtonItem;
    }
    
    func openMenu(sender:UIButton){
        var frame = self.navigationController!.navigationBar.frame;
        frame.origin.x = self.navigationItem.rightBarButtonItem!.customView!.frame.origin.x;
        frame.size.width = self.navigationItem.rightBarButtonItem!.customView!.frame.width;
        
        var chat = KxMenuItem("群聊",image: nil,target: self,action: Selector("chat:"));
        var edit = KxMenuItem("修改",image: nil,target: self,action: Selector("edit:"));
        var remove = KxMenuItem("删除",image: nil,target: self,action: Selector("deleteGroup:"));
        KxMenu.setTitleFont(Utils.defaultFont());
        KxMenu.showMenuInView(self.navigationController!.view, fromRect: frame, menuItems: [chat,edit,remove]);
    }
    
    func chat(menuItem:KxMenuItem){
        
    }
    
    func edit(menuItem:KxMenuItem){
        let storyboard = UIStoryboard(name: "Main", bundle: nil);
        let editGroupViewController = storyboard.instantiateViewControllerWithIdentifier("createOrUpdateGroupView") as CreateOrUpdateGroupViewController;
        editGroupViewController.edit(groupInfo);
        self.navigationController?.pushViewController(editGroupViewController, animated: true);
    }
    
    func deleteGroup(menuItem:KxMenuItem){
        ConfirmView(message: "确定删除此群?\n(删除后不可恢复)", confirm: { () -> Void in
            var groupGuid = self.groupInfo.objectForKey("guid") as String;
            var url = "/api/v1/group?groupGuid=\(groupGuid)";
            HttpUtils.sendRequest(url, method: RequestMethod.DELETE, httpBody: nil, successHandle: { (response) -> Void in
                Utils.debug("Delete group the guid [\(groupGuid)]");
                self.navigationController?.popViewControllerAnimated(true);
                }, errorHandle: { (error) -> Void in
            });
            }, cancel: nil).show();
    }
    
    func loadGroupDetails(groupGuid:String){
        self.processing();
        var url = "/api/v1/group?groupGuid=\(groupGuid)";
        HttpUtils.sendRequest(url, method: RequestMethod.GET, httpBody: nil, successHandle: { (response) -> Void in
            var groupDetails = response as NSDictionary;
            var groupOwner = groupDetails.objectForKey("owner") as NSMutableDictionary;
            self.ownerGuid = groupOwner.objectForKey("guid") as String;
            self.groupParticipantsAmount = groupDetails.objectForKey("participantsAmount") as Int;
            self.dataSource = groupDetails.objectForKey("dataSource") as [NSMutableDictionary];
            self.tableView.reloadData();
            self.processComplete();
            
            var groupName = groupDetails.objectForKey("name") as String;
            var access = groupDetails.objectForKey("access") as String;
            var description = groupDetails.objectForKey("description") as String;
            var groupInfo = NSMutableDictionary();
            groupInfo.setObject(groupGuid, forKey: "guid");
            groupInfo.setObject(groupName, forKey: "name");
            groupInfo.setObject(access, forKey: "access");
            groupInfo.setObject(description, forKey: "description");
            self.groupInfo = groupInfo;
            }, errorHandle: { (error) -> Void in
            self.processComplete();
        });
    }
    
    func updateTitile(){
        var groupName = self.groupInfo.objectForKey("name") as String;
        self.navigationItem.titleView = ViewUtils.titleView(groupName);
    }
    
    // Back action handler
    func back(barButtonItem:UIBarButtonItem){
        self.navigationController?.popViewControllerAnimated(true);
    }
    
    
    // Implement JoinRequests table UITableViewDataSource
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count;
    }
    
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var dictionary = self.dataSource[indexPath.row] as NSDictionary;
        var isRequest = dictionary.objectForKey("isRequest") as Bool;
        if(isRequest){
            var cell = GroupRequestCell.create(indexPath, width: tableView.frame.width, request: dictionary);
            return cell;
        } else {
            var user = dictionary.objectForKey("user") as NSMutableDictionary;
            var cell = GroupPersionalCell.create(tableView.frame.width, user: user,ownerGuid: self.ownerGuid);
            return cell;
        }
    }
    
    func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        var dictionary = self.dataSource[indexPath.row] as NSDictionary;
        var isRequest = dictionary.objectForKey("isRequest") as Bool;
        if(isRequest){
            return true;
        }
        
        var user = dictionary.objectForKey("user") as NSDictionary;
        var userGuid = user.objectForKey("guid") as String;
        return (self.ownerGuid != userGuid);
    }
    
    func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {
        var dictionary = self.dataSource[indexPath.row] as NSDictionary;
        var isRequest = dictionary.objectForKey("isRequest") as Bool;
        if(isRequest){
            var rejectRequestAction = UITableViewRowAction(style: UITableViewRowActionStyle.Normal, title: "",handler:rejectRequestHandler);
            rejectRequestAction.backgroundColor = UIColor(patternImage: UIImage(named: "close_in_row")!);
            var acceptRequestAction = UITableViewRowAction(style: UITableViewRowActionStyle.Normal, title: "",handler:acceptRequestHandler);
            acceptRequestAction.backgroundColor = UIColor(patternImage: UIImage(named: "ok_in_row")!);
            return [rejectRequestAction,acceptRequestAction];
        }
        
        var removeAction = UITableViewRowAction(style: UITableViewRowActionStyle.Normal, title: "", handler: { (action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in
            self.removeParticipantFromJoinedList(tableView, action: action, indexPath: indexPath);
        });
        removeAction.backgroundColor = UIColor(patternImage: UIImage(named: "close_in_row")!);
        return [removeAction];
    }
    
    func removeParticipantFromJoinedList(tableView:UITableView,action:UITableViewRowAction!, indexPath:NSIndexPath!){
        ConfirmView(message: "确定移除此小伙伴?", confirm: { () -> Void in
            var url = "/api/v1/group/leave";
            var participant = self.dataSource[indexPath.row] as NSDictionary;
            var user = participant.objectForKey("user") as NSDictionary;
            var userGuid = user.objectForKey("guid") as String;
            var groupGuid = self.groupInfo.objectForKey("guid") as String;
            var postBody = NSMutableDictionary();
            postBody.setObject(groupGuid, forKey: "groupGuid");
            postBody.setObject(userGuid, forKey: "userGuid");
            HttpUtils.sendRequest(url, method: RequestMethod.POST, httpBody: postBody, successHandle: { (response) -> Void in
                self.dataSource.removeAtIndex(indexPath.row);
                self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic);
                self.groupParticipantsAmount--;
                self.updateTitile();
                }, errorHandle: { (error) -> Void in
                    
            });
            }, cancel: nil).show();
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        var dictionary = self.dataSource[indexPath.row] as NSDictionary;
        var isRequest = dictionary.objectForKey("isRequest") as Bool;
        var userGuid = "";
        if(isRequest){
            var sender = dictionary.objectForKey("sender") as NSDictionary;
            userGuid = sender.objectForKey("guid") as String;
        } else {
            var user = dictionary.objectForKey("user") as NSDictionary;
            userGuid = user.objectForKey("guid") as String;
        }
        var isCurrentUser = Utils.isCurrentUser(userGuid);
        if(isCurrentUser){
            var tabBarController = self.tabBarController as PureTennisTabBarController;
            tabBarController.toggleView(tabBarController.customItems.last!);
        } else {
            var userDetailsViewController = UserDetailsViewController();
            userDetailsViewController.guid = userGuid
            userDetailsViewController.loadUserDetails();
            self.navigationController!.pushViewController(userDetailsViewController, animated: true);
        }
    }
    
    func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        
    }
    
    // rejectRequestHandler
    func rejectRequestHandler(tableViewRowAction:UITableViewRowAction!,indexPath:NSIndexPath!){
        var url = "/api/v1/group/joinrequest/reject";
        self.joinRequestHandle(url, operation: RequestOperation.Reject, indexPath: indexPath);
    }
    
    // acceptRequestHandler
    func acceptRequestHandler(tableViewRowAction:UITableViewRowAction!,indexPath:NSIndexPath!){
        var url = "/api/v1/group/joinrequest/accept";
        self.joinRequestHandle(url, operation: RequestOperation.Accept, indexPath: indexPath);
        
      }
    
    func joinRequestHandle(url:String,operation:RequestOperation,indexPath:NSIndexPath){
        var joinRequest = self.dataSource[indexPath.row] as NSMutableDictionary;
        var joinRequestGuid = joinRequest.objectForKey("guid") as String;
        var postData = NSMutableDictionary();
        postData.setObject(joinRequestGuid, forKey: "guid");
        
        HttpUtils.sendRequest(url, method: RequestMethod.POST, httpBody: postData, successHandle: { (response) -> Void in
            var groupGuid = self.groupInfo.objectForKey("guid") as String;
            self.loadGroupDetails(groupGuid);
            self.updateTabBarBadge();
        }, errorHandle: { (error) -> Void in
            
        });
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        Utils.debug("Memory warning")
    }
    
    enum RequestOperation{
        case Reject;
        case Accept;
    }
}


